package com.xiaocz.hblsubstitutedriving.activities.activity;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;
import com.google.gson.reflect.TypeToken;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.activities.activity.dialog.AdvertisingActivity;
import com.xiaocz.hblsubstitutedriving.activities.fragment.dialog.CallPhoneDialogFragment;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.model.VersionUpdate;

import java.io.IOException;
import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Time:2019/9/16
 * Created by xiaocz
 * Describe 客服中心
 */
public class CustomerCenterActivity extends BaseActivity {

    @BindView(R.id.tv_update_version)
    TextView tvVersion;

    public static void show(Context context) {
        Intent intent = new Intent(context, CustomerCenterActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initData() {
        super.initData();
        StringBuilder builder = new StringBuilder();
        builder.append("版本更新（当前版本");
        builder.append(getVersionName());
        builder.append(")");
        tvVersion.setText(builder);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_customer_center;
    }

    @OnClick({R.id.tv_update_version,R.id.tv_terms_for_usage,R.id.tv_update_pwd,R.id.tv_xcx,R.id.tv_official_accounts,R.id.tv_phone,R.id.tv_zlh})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_update_version://版本更新
                getUpdateVersion();
                break;
            case R.id.tv_terms_for_usage://注册使用及服务条款
                WebViewActivity.show(mContext, Common.Constant.API_H5 + "Driver/RegisterAgreement");
                break;
            case R.id.tv_update_pwd://修改登录密码
                UpdatePwdActivity.show(mContext);
                break;
            case R.id.tv_xcx://小程序
                AdvertisingActivity.show(mContext);
                break;
            case R.id.tv_official_accounts://公众号
                ImageViewActivity.show(mContext,1);
                break;
            case R.id.tv_phone://客服电话
                ImageViewActivity.show(mContext,2);
                break;
            case R.id.tv_zlh:
                ImageViewActivity.show(mContext,3);
                break;
        }
    }


    /**
     * 版本更新
     */
    public void getUpdateVersion() {
        loadingDialogShow(true);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        okHttpClient.post(Common.Constant.API_IP + "api/Common/getUpdateInfo", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                App.getInstance().showMessage(getResources().getString(R.string.network_timeout));
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<VersionUpdate>>() {
                }.getType();
                RspModel<VersionUpdate> rspModel = getAnalysis(response, type, "版本更新");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        try {
                            int versionCode = getVersionCode();
                            if (rspModel.getData().getVersion() > versionCode) {
                                updateVersion(rspModel.getData().getIs_forced(), rspModel.getData().getDescription(), rspModel.getData().getApk_url());
                            } else {
                                App.getInstance().showMessage("当前已是最新版本！");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    private void updateVersion(int force, String content, String url) {
        DownloadBuilder downloadBuilder = AllenVersionChecker.getInstance().downloadOnly(
                UIData.create().setTitle("是否更新?").setContent(content).setDownloadUrl(url)
        );
        downloadBuilder.setSilentDownload(false); //默认false
        downloadBuilder.setForceRedownload(true); //默认false 本地有安装包缓存也会重新下载apk
        downloadBuilder.executeMission(mContext);
        //强制更新
        if (force == 1) {
            //是否显示下载对话框
            downloadBuilder.setShowDownloadingDialog(true);// 默认true
            downloadBuilder.setForceUpdateListener(new ForceUpdateListener() {
                @Override
                public void onShouldForceUpdate() {
                }
            });
        }else {
            downloadBuilder.setShowDownloadingDialog(false);
        }
    }

    /**
     * 显示拨打电话的dialog对象
     */
    private void showCallPhoneDialogFragment(String tel) {
        CallPhoneDialogFragment fragment = CallPhoneDialogFragment.newInstance(tel);
        if (!fragment.isAdded()) {
            fragment.show(getSupportFragmentManager(), fragment.getClass().getName());
        }
    }

}
